import AStarManager from "./common/AStarManager.js"
import MapRect from "./common/MapRect.js"
import RectType from "./common/RectType.js"
import GameConfig from "./config/GameConfig.js"


const MAP_ROW = 30
const MAP_COL = 10

const canvas = document.getElementById('canvas') as HTMLCanvasElement
const context = canvas.getContext('2d')
canvas.width = MAP_ROW * 50
canvas.height = MAP_COL * 50
document.addEventListener('contextmenu',function(e){
    e.preventDefault()
})

const MapData = new Array<Array<MapRect>>()

function Random(min: number, max: number) {
    return Math.floor(Math.random() * (max - min + 1) + min)
}

function initMap() {
    for (let i = 0; i < MAP_ROW; i++) {
        MapData[i] = new Array<MapRect>()
        for (let j = 0; j < MAP_COL; j++) {
            const tile = new MapRect(i, j)
            tile.type = Random(1, 100) < 20 ? RectType.Obstacles : RectType.Ground
            MapData[i][j] = tile
        }
    }
}

initMap()


function drawMap() {
    if (!context) return

    context.clearRect(0,0,500,500)

    MapData.forEach(array => {
        array.forEach(tile => {
            tile.draw(context)
        })
    })
}

drawMap()

let startPoint: MapRect
let endPoint: MapRect
const mgr = new AStarManager(MapData)
let path:Array<MapRect>|null = null

canvas.addEventListener('mousedown', e => {
    console.log(e);
    const x = Math.floor(e.offsetX / GameConfig.RectSize)
    const y = Math.floor(e.offsetY / GameConfig.RectSize)
    const current = MapData[x][y]
    current.type = RectType.Border
    if (e.button == 2) {
        endPoint = current
    } else {
        startPoint = current
    }

    if (startPoint && endPoint) {
        path && path.forEach(tile=>tile.type = RectType.Ground)
        console.log(`start point is:(${startPoint.x},${startPoint.y}, end point is :(${endPoint.x},${endPoint.y}))`)
        path = mgr.calc(startPoint, endPoint)        
        if(path){
            console.log(path)
            const timer = setInterval(()=>{
                // rEach(tile=>tile.type = RectType.Border)
                const tile = path?.find(tile=>tile.type == RectType.Ground)
                tile && (tile.type = RectType.Border)
                drawMap()
                if(!path?.find(tile=>tile.type == RectType.Ground)){
                    clearInterval(timer)
                }
            },100)
        }
    }


    // drawMap()
})
